#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import shlex
import platform
from typing import Union

# 黑名单（防炸服）
DANGEROUS_CMDS = ['rm', 'shutdown', 'reboot', 'halt', 'mkfs', 'dd', ':>', 'format']


def exec_shell(command: Union[str, list], timeout: int = 10) -> dict:
    """
    跨平台通用终端命令执行器，支持 str 或 list 类型命令

    Args:
        command (str | list): 命令字符串或命令列表
        timeout (int): 超时秒数

    Returns:
        dict: {
            "code": int,
            "stdout": str,
            "stderr": str,
            "success": bool
        }
    """
    # 判空
    if not command or (isinstance(command, str) and not command.strip()):
        return {
            "code": -1,
            "stdout": "",
            "stderr": "空命令",
            "success": False
        }

    # 拼接用于黑名单检测的命令字符串
    command_str = command if isinstance(command, str) else ' '.join(map(str, command))

    if any(bad in command_str for bad in DANGEROUS_CMDS):
        return {
            "code": -1,
            "stdout": "",
            "stderr": f"禁止执行危险命令: {command_str}",
            "success": False
        }

    is_windows = platform.system() == 'Windows'
    use_shell = is_windows and isinstance(command, str)

    try:
        result = subprocess.run(
            command if isinstance(command, list) else shlex.split(command),
            shell=use_shell,
            capture_output=True,
            text=True,
            timeout=timeout
        )

        return {
            "code": result.returncode,
            "stdout": result.stdout.strip(),
            "stderr": result.stderr.strip(),
            "success": result.returncode == 0
        }

    except subprocess.TimeoutExpired:
        return {
            "code": -2,
            "stdout": "",
            "stderr": "命令执行超时",
            "success": False
        }

    except Exception as e:
        return {
            "code": -99,
            "stdout": "",
            "stderr": f"执行出错: {str(e)}",
            "success": False
        }


if __name__ == '__main__':
    # 支持字符串命令
    print(exec_shell("echo hello"))
    # 支持命令列表
    print(exec_shell(["iptables", "-D", "OUTPUT", "-p", "tcp", "--sport", "1230"]))
